import axios from 'axios';
import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input,message,Upload } from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined,PlusOutlined,EllipsisOutlined  } from '@ant-design/icons'
import { useForm } from 'antd/lib/form/Form';
import { useParams } from 'react-router-dom';
import moment from 'moment';
const { TextArea } = Input;
const Homework = () => {
    let { id } = useParams(); // 使用useParams hook获取URL参数中的id
    const navigate = useNavigate();
  const [form] = useForm();
  const [data, setData] = useState([]);
  const [length, setlength] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isaddModalVisible, setIsaddModalVisible] = useState(false);
  const [iscourseModalVisible, setIscourseModalVisible] = useState(false);
  const [editedData, setEditedData] = useState(null);
  const [addData, setaddData] = useState(null);
  const [params,setParams] = useState({
    page:1,
    perpage:5
  })
  const [fileList, setFileList] = useState([]);
  const [startDate, setStartDate] = useState(null);
  const [showUpload, setShowUpload] = useState(false); // 控制Upload组件显示与隐藏的状态
  

  useEffect(() => {
    axios.get('http://localhost:8000/getteacherhomework',{params: { ...params, id } })
      .then(response => {
        console.log("接受到的数据"+response.data.list);
        setData(response.data.list);
        setlength(response.data.length);
        console.log("存储到的数据"+JSON.stringify(data));
       // console.log(params); // Updated data
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, [params]);
  

  // 翻页实现
  const pageChange = (page) => {
    setParams({
      ...params,
      page
    })
  }

  // 删除
  
  const del = async (data) => {
    console.log(data.id);
    console.log(data.img);
    // 弹窗确认是否删除
    const confirmDelete = window.confirm("确定要删除吗？");
    
    if (confirmDelete) {
      try {
        if (data.img) {
            // 如果 data.img 存在，则发送带有 img 参数的请求
            await axios.delete(`http://localhost:8000/deletehomework/${data.id}/${data.img}`);
        } else {
            // 如果 data.img 不存在，则发送不带 img 参数的请求
            await axios.delete(`http://localhost:8000/deletehomeworks/${data.id}`);
        }


            
            // 更新 params 以触发重新获取数据
            axios.get('http://localhost:8000/getteacherhomework', { params: { ...params, id } })
                .then(response => {
                    //console.log("接受到的数据" + response.data.list);
                    setData(response.data.list);
                    setlength(response.data.length);
                    //console.log("存储到的数据" + JSON.stringify(data));
                    // console.log(params); // Updated data
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                });
                
            message.success('删除成功');
        } catch (error) {
            //console.error('删除数据时发生错误:', error);
        }
    }
};

const change = (data) => {
  console.log(data);
  setEditedData(data);
  setFileList("")
  setShowUpload(false)
  setIsModalVisible(true);
}
const formatDateTime = (dateTimeString) => {
  const dateTime = new Date(dateTimeString);
  const formattedDateTime = dateTime.toISOString().slice(0, 16); // 使用 toISOString 方法转换日期时间格式，只取前16位字符
  return formattedDateTime;
};


  useEffect(() => {
    //console.log(editedData);
    if (editedData !== null) {
      form.setFieldsValue({
        homeworkid: editedData?.homeworkid,
        title: editedData?.title,
        text: editedData?.text,
        img: editedData?.img,
        start: editedData?.start,
        end: editedData?.end,
        // 其他字段...
      });
      setIsModalVisible(true);
    }
  }, [editedData, form]);

  const handleOk = () => {
    const Id = editedData?.id;
    const values = form.getFieldsValue(); // 获取表单修改后的值
    if (fileList && fileList.length > 0) {
      // fileList 有值
      console.log('fileList 有值');
      values.img = []; // 初始化存放每一项的response的数组
    
    fileList.forEach(item => {
        values.img.push(item.response); // 把filelist里每一项的response都存进values.img里
    });
     values.img = values.img.join(', ');
      // 执行相关操作
  } else {
      // fileList 无值
      console.log('fileList 无值');
      // 执行其他操作或者提示用户上传文件
  }
    console.log('修改后的表单值:', values, id);
    axios.post('http://localhost:8000/changehomework', { Id, values,params })
      .then(response => {
        // 处理来自后端的响应
        console.log('成功发送到后端并收到响应:', response.data);
        setIsModalVisible(false);
        axios.get('http://localhost:8000/getteacherhomework',{params: { ...params, id } })
        .then(response => {
          setData(response.data.list);
          setlength(response.data.length);
         // console.log(params); // Updated data
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
      });
  };
  

  const handleCancel = () => {
    setIsModalVisible(false);
    //setEditedData([])
    
  };


  
  const add = (data) => {
    //console.log(data);
    setaddData(data);
    setIsaddModalVisible(true);
  }

  useEffect(() => {
    //console.log(addData);
    if (addData !== null) {
      form.setFieldsValue({
        homeworkid: addData?.homeworkid,
        title: addData?.title,
        text: addData?.text,
        img: addData?.img,
        start: addData?.start,
        end: addData?.end,
        // 其他字段...
      });
      setIsaddModalVisible(true);
    }
  }, [addData, form]);

  const addOk = () => {
    const updatedValues = form.getFieldsValue(); // 获取表单修改后的值
    const anyValueEmpty = Object.values(updatedValues).some(value => !value); // 检查是否有任何值为空
    const teacherid = localStorage.getItem('teacherid');
    const name = localStorage.getItem('usersname');
    const values = {
      ...updatedValues,
      courseid: id, // 假设 id 是从 localStorage 中获取的
      teacherid: teacherid, // 将 teacherid 添加到表单值中
      teachername: name, // 将 name 添加到表单值中
    };
    if (anyValueEmpty) {
        message.error('表单值存在空值，不执行请求');
        return;
    }
    values.img = []; // 初始化存放每一项的response的数组
    
    fileList.forEach(item => {
        values.img.push(item.response); // 把filelist里每一项的response都存进values.img里
    });
     values.img = values.img.join(', ');
    console.log('修改添加值:', teacherid,name,id);
    console.log('修改后的表单值:', values);
    axios.post('http://localhost:8000/addhomework', { values })
        .then(response => {
            console.log('成功发送到后端并收到响应:', response.data);
            setIsaddModalVisible(false);
            
            axios.get('http://localhost:8000/getteacherhomework',{params: { ...params, id } })
            .then(response => {
              //console.log("接受到的数据"+response.data.list);
              setData(response.data.list);
              setlength(response.data.length);
              //console.log("存储到的数据"+JSON.stringify(data));
             // console.log(params); // Updated data
            })
            .catch(error => {
              console.error('Error fetching data:', error);
            });
            form.resetFields(); 
        })
        .catch(error => {
            console.error('与后端通信时发生错误:', error);
        });
        setFileList([]);
};
 

const handleChange = info => {
  let fileList = [...info.fileList];
  fileList = fileList.slice(-3); // 最多显示3个文件

  // 更新 fileList 状态
  setFileList(fileList);
  console.log(fileList);

  if (info.file.status === 'done') {
    message.success(`${info.file.name} 文件上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败`);
  }
};

const handleCustomRequest = async (options) => {
  const { file, onSuccess, onError } = options;

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await fetch("http://localhost:8000/homeworkupload", {
      method: "POST",
      body: formData,
    });
    if (response.ok) {
      const data = await response.json();
      const newFilename = data.newFilename;
      console.log(newFilename);
      onSuccess(newFilename); // 将 newFilename 传递给 onSuccess
      console.log(fileList);
  } else {
      onError(); // 文件上传失败
  }
  } catch (error) {
    console.error("Error uploading file:", error);
    onError(); // 文件上传失败
  }
};
const handleRemove = file => {
  const imageData = file.response;

  console.log('要删除的图片信息:', imageData);

  // 使用 axios 发送 DELETE 请求
  axios.post('http://localhost:8000/teacherupload', { imageData })
  .then(response => {
      console.log('成功删除服务器上的图片');
      message.success(`文件删除成功`);
      // 可以在这里执行其他操作
  })
  .catch(error => {
      console.error('删除图片时出错:', error);
  });
  console.log(fileList);

};


  const addCancel = () => {
    setIsaddModalVisible(false);
    //setEditedData([])
  };

  const takecourse= (data) => {
    console.log(data.courseid);
    console.log(data.homeworkid);
    navigate(`/Layoutteacher/correct/${data.courseid}/${data.homeworkid}`);

    //setEditedData([])
  };

  const takeCancel = () => {
    setIscourseModalVisible(false);
    //setEditedData([])
  };

  const handleUploadButtonClick = () => {
    // 点击重新上传图片按钮时触发的函数
    setFileList([]); // 清空已有的文件列表
    setShowUpload(true); // 显示Upload组件

    // 打印 editedData.img 的值
    console.log('editedData.img:', editedData.img);
    axios.post('http://localhost:8000/delimg', {
      imageToDelete: editedData.img,
      Id: editedData.id 
    })
    .then(response => {
      if (response.status === 200) {
        console.log('Image deleted successfully.');
      } else {
        console.error('Failed to delete image.');
      }
    })
    .catch(error => {
      console.error('Error deleting image:', error);
    });
  };

  const columns = [
    {
      title: '作业编号',
      dataIndex: 'homeworkid',
      width: 220
    },
    {
      title: '作业标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      width: 220,
      render: data => {
          if (!data.start || !data.end) {
              return '未知';
          }

          const now = new Date();
          const startDate = new Date(data.start);
          const endDate = new Date(data.end);

          if (now < startDate) {
              return '未发布';
          } else if (now >= startDate && now <= endDate) {
              return '进行中';
          } else {
              return '已截止';
          }
      }
  },
    {
      title: '操作',
      width: 220,
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => change(data)}  
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => del(data)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<EllipsisOutlined />}
              style={{ color: 'white', backgroundColor: 'black' }}
              onClick={() => takecourse(data)}
            />
          </Space>
        )
      },
      fixed: 'right'
    }
  ]

  return (
    <div>
      <Breadcrumb>
        <Breadcrumb.Item><Link to="/Layoutteacher/coursepage">Courses</Link></Breadcrumb.Item>
        <Breadcrumb.Item><Link to={`/Layoutteacher/course/${id}`}>课程详情</Link></Breadcrumb.Item>
        <Breadcrumb.Item>作业管理</Breadcrumb.Item>
      </Breadcrumb>
    <h1>作业管理</h1>
      <Card>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={add}
          style={{ marginLeft: 10 }}
        >
          创建新任务
        </Button>
      </Card>
      <Card title={`共创建 ${length} 个作业：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          pagination={
            {
              pageSize: params.perpage,
              onChange: pageChange,
              current: params.page,
              total: length
            }
          }
        />
      </Card>
      <Modal
  title="修改作业信息"
  visible={isModalVisible}
  onOk={handleOk}
  onCancel={handleCancel}
  width={800}
>
  <Form
    form={form}
    labelCol={{ span: 6 }}
    wrapperCol={{ span: 16 }}
  >
    {/* 表单字段 */}
    <Form.Item label="作业编号" name="homeworkid" initialValue={editedData?.homeworkid}>
      <Input style={{ width: 200 }} />
    </Form.Item>
    <Form.Item label="作业标题" name="title" initialValue={editedData?.title}>
      <Input placeholder="请输入文章标题" style={{ width: 400 }} />
    </Form.Item>
    <Form.Item label="作业内容" name="text" initialValue={editedData?.text}>
      <TextArea rows={8} />
    </Form.Item>
    <Form.Item
      label="图片列表"
      initialValue={editedData?.img}
      name="img"
    >
      <div style={{ marginBottom: '16px' }}>
        {/* 根据 editedData?.img 中的链接显示图片 */}
        {editedData?.img && (
          editedData.img.includes(',') ? 
            editedData.img.split(',').map((img, index) => (
              <img key={index} src={`http://localhost:8000/${img.trim()}`} alt={`Image ${index}`} style={{ maxWidth: '100px', maxHeight: '100px', marginRight: '10px' }} />
            )) : 
            <img src={`http://localhost:8000/${editedData.img.trim()}`} alt="Single Image" style={{ maxWidth: '100px', maxHeight: '100px' }} />
        )}
      </div>

      <Button onClick={handleUploadButtonClick}>删除图片,重新上传</Button>

      {/* 根据showUpload状态控制Upload组件的显示与隐藏 */}
      {showUpload && (
  <Upload
  listType="picture-card"
  customRequest={handleCustomRequest}
  fileList={fileList}
  onChange={handleChange}
  onRemove={handleRemove} // 添加 onRemove 事件处理程序
>
  {fileList.length < 3 && '+ 上传'}
</Upload>
      )}
    </Form.Item>
    
    <Form.Item label="发布时间" name="start" initialValue={editedData?.start}>
      <Input  style={{ width: '100%' }} />
    </Form.Item>

<Form.Item label="截止时间" name="end" initialValue={editedData?.end}>
  <Input  style={{ width: '100%' }} />
</Form.Item>

  </Form>
</Modal>

      <Modal
        title="创建新任务"
        visible={isaddModalVisible}
        onOk={addOk}
        onCancel={addCancel}
        width={800} // 设置宽度为800像素
        height={800} // 设置高度为600像素
      >
        <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        >
          {/* 这里添加表单字段，用于修改数据 */}
          <Form.Item label="作业编号" name="homeworkid" initialValue={addData?.homeworkid}>
            <Input style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="作业标题" name="title" initialValue={addData?.title}>
          <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item label="作业内容" name="text" initialValue={addData?.text}>
          <TextArea rows={8} />
          </Form.Item>
          
          <Form.Item
  label="图片列表"
>
  <Upload
    listType="picture-card"
    customRequest={handleCustomRequest}
    fileList={fileList}
    onChange={handleChange}
    onRemove={handleRemove} // 添加 onRemove 事件处理程序
  >
    {fileList.length < 3 && '+ 上传'}
  </Upload>
</Form.Item>
           
<Form.Item
  label="发布时间"
  name="start"
  initialValue={addData?.startTime}
>
  <Input type="datetime-local" style={{ width: '100%' }} />
</Form.Item>

<Form.Item
  label="截止时间"
  name="end"
  initialValue={addData?.deadline}
  rules={[
    {
      validator: (_, value) => {
        if (value && value <= form.getFieldValue('start')) {
          return Promise.reject('截止时间必须在发布时间后面');
        }
        return Promise.resolve();
      },
    },
  ]}
>
  <Input type="datetime-local" style={{ width: '100%' }} />
</Form.Item>



          {/* 添加其他表单字段... */}
        </Form>
      </Modal>

      <Modal
  title="任教课程"
  visible={iscourseModalVisible}
  onOk={null}
  onCancel={takeCancel}
  footer={null} 
>

</Modal>

    </div>
  );
};

export default  Homework;